<template>
  <div class="time-wrapper">
    <el-date-picker
      v-if="isShow"
      ref="dateRef"
      v-model="innerValue"
      v-bind="$attrs"
      :format="curformat"
      @change="handleChange"
    >
      <template v-for="(item, key, index) in $slots" :key="index" v-slot:[key]>
        <slot :name="key"></slot>
      </template>
    </el-date-picker>
  </div>
</template>
<script>
import { ElDatePicker, ElMessageBox } from 'element-plus';
import moment from 'moment-timezone';

export default {
  name: 'dateTime',
  components: { ElDatePicker },
  props: {
    modelValue: [Date, Number, String, Array],
    isShowDST: {
      type: Boolean,
      default: false,
    },
    lang: {
      type: Object,
    },
  },
  watch: {
    modelValue: {
      handler() {
        this.initValue();
      },
    },
  },
  emits: [
    'update:modelValue',
    'change',
    'changeTiemVlaue',
    'getUTC',
    'getTimeLabel',
  ],
  data() {
    return {
      timeZone: 'Australia/Sydney',
      curformat: 'YYYY-MM-DD HH:mm:ss',
      curValue: '',
      innerValue: '',
      curValueformat: 'YYYY-MM-DD HH:mm:ss',
      count: 0,
      locale: null,
      isShow: true,
      inputNode: null,
      curInputValue: '',
      isLabelDST: false,
    };
  },
  created() {},
  mounted() {
    this.initValue();
  },
  methods: {
    initValue() {
      this.innerValue = this.getFormatLabel(this.modelValue) || this.modelValue;
      this.curformat = this.$attrs.format;
      console.log('curValue', this.curValue, this.modelValue);
    },
    // 判断curValue 传递过字符串是否包含(DST)
    judgeIsDSTLabel(label) {
      if (typeof label === 'string' && label.indexOf(' (DST)') > -1) {
        this.isLabelDST = true;
      } else {
        this.isLabelDST = false;
      }
    },
    getDomLabel() {
      this.$nextTick(() => {
        // this.inputNode =
        //   this.$refs.dateRef.$el.parentNode.querySelectorAll('.el-range-input');
        // console.log(' this.$refs.dateRef', this.inputNode);
        // let arr = Array.from(this.inputNode);
        // arr[1].insertAdjacentHTML('afterend', arr[1].outerHTML);
        // arr[0].insertAdjacentHTML('afterend', arr[1].outerHTML);
        // arr[0].parentNode.removeChild(arr[0]);
        // arr[1].parentNode.removeChild(arr[1]);
        // // setTimeout(() => {
        //   this.inputNode =
        //     this.$refs.dateRef.$el.parentNode.querySelectorAll(
        //       '.el-range-input',
        //     );
        //   arr = Array.from(this.inputNode);
        //   arr[0].value = 'zzzzzz (DST)';
        //   arr[1].value = 'zzzz (DST)';
        // });
      });
    },
    handleDomInput(dom) {
      console.log('xxx', dom.target.value);
      this.curInputValue = dom.target.value;
    },
    handleChange(value) {
      console.log('change', value, this.curInputValue);
      // this.handleDealTime(value);

      this.$emit('change', moment(value).format('z'));
    },
    handleBlur() {
      console.log(' handleBlur curValue', this.curValue, this.curInputValue);
      console.log(' handleBlur curInputValue', this.curInputValue);
      // console.log(' handleBlur inputNode', this.inputNode.value);
    },
    handleDealTime(value) {
      if (value) {
        if (Array.isArray(value)) {
          this.handleMultileOpenBox(value);
        } else {
          this.handleSingleOpenBox(
            this.isDSTOverlap(this.getFormatLabel(value)),
            this.getFormatLabel(value),
          );
        }
      }
    },
    //
    handleMultileOpenBox(valueArr) {
      let tmpArr = valueArr.map((v) => {
        return {
          isDSTOverlap: this.isDSTOverlap(this.getFormatLabel(v)),
          getFormatLabel: this.getFormatLabel(v),
        };
      });
      let reusltLabel = tmpArr
        .filter((v) => {
          return v.isDSTOverlap;
        })
        .map((v) => {
          return `该${v.getFormatLabel}时间段夏令时时间重复 请选择是否是夏令时\n`;
        })
        .join('\n');

      if (reusltLabel) {
        this.handdleGetBox(
          reusltLabel,
          () => {
            let realUTCTimeArr = [];
            let tmpFormatArr = [];
            tmpArr.forEach((e) => {
              let item = {};
              if (e.isDSTOverlap) {
                item = this.handleGetDSTUTCObj(e.getFormatLabel);
              } else {
                item = this.handleGetUTCObj(e.getFormatLabel);
              }
              realUTCTimeArr.push(item.realUTCTime);
              tmpFormatArr.push(item.tmpFormat);
            });
            this._showDSTLabel(true);
            this.$refs.dateRef.handleClose();
            this.isShow = false;
            setTimeout(() => {
              this.isShow = true;
            }, 200);

            this.$emit('getUTC', realUTCTimeArr);
            this.$emit('getTimeLabel', tmpFormatArr);
          },
          () => {
            this._showDSTLabel(false);
            this.handleDispatchMutil(tmpArr);
            this.$refs.dateRef.handleClose();
          },
        );
      } else {
        this.handleDispatchMutil(tmpArr);
      }
    },
    handleDispatchMutil(tmpArr) {
      let realUTCTimeArr = [];
      let tmpFormatArr = [];
      tmpArr.forEach((e) => {
        let item = {};
        item = this.handleGetUTCObj(e.getFormatLabel);
        realUTCTimeArr.push(item.realUTCTime);
        tmpFormatArr.push(item.tmpFormat);
      });
      this.$emit('getUTC', realUTCTimeArr);
      this.$emit('getTimeLabel', tmpFormatArr);
    },

    handleSingleOpenBox(isDSTOverlap, value) {
      if (isDSTOverlap) {
        if (this.isLabelDST) {
          this.handleAddSelecDST(value);
          return;
        }
        let contentLabel = `该${value}时间段夏令时时间重复 请选择是否是夏令时`;
        this.handdleGetBox(
          contentLabel,
          () => {
            this.handleAddSelecDST(value);
          },
          () => {
            this.curformat = `${this.$attrs.format}`;
            this._showDSTLabel(false);
            this.handleDispatch();
            this.$refs.dateRef.handleClose();
          },
        );
      } else {
        this._showDSTLabel(this.isShowDST && this.isDSTFun());
        this.handleDispatch();
      }
    },

    handdleGetBox(content, sucCallBack, cancelCallBack) {
      ElMessageBox.confirm(content, 'Warning', {
        confirmButtonText: '夏令时',
        cancelButtonText: '非夏令时',
        type: 'warning',
      })
        .then(() => {
          sucCallBack && sucCallBack();
        })
        .catch(() => {
          cancelCallBack && cancelCallBack();
        });
    },

    isDSTOverlap(dateTime, timeZone) {
      // 将给定的时间转换为moment对象，并设定其时区
      let time = moment.tz(dateTime, null, timeZone || this.timeZone);
      // 为了检测重叠，观察当前时间向前和向后推移一小时后的时间是否还在DST中
      let beforeHour = time.clone().subtract(1, 'hour');
      let afterHour = time.clone().add(1, 'hour');
      // 检查当前时间与前后各一小时的DST状态是否有变化
      // 如果在当前时间是DST结束的第一个小时内，那么向前推一个小时将会退出DST模式
      return time.isDST() && beforeHour.isDST() && !afterHour.isDST();
    },

    handleDispatch() {
      this.$emit('getUTC', this._getUTC());
      this.$emit('getTimeLabel', this.getFormatLabel());
    },

    // 选择单个的
    handleAddSelecDST(valueLabel) {
      this._showDSTLabel(this.isShowDST && true);
      this.$refs.dateRef.handleClose();
      const { realUTCTime, tmpFormat } = this.handleGetDSTUTCObj(valueLabel);
      this.$emit('getUTC', realUTCTime);
      this.$emit('getTimeLabel', tmpFormat);
    },
    handleGetUTCObj(valueLabel) {
      let realUTCTime = moment.tz(valueLabel, null, this.timeZone).utc();
      let tmpFormat = moment
        .tz(realUTCTime, null, this.timeZone)
        .format(this.$attrs.format);
      return {
        realUTCTime,
        tmpFormat,
      };
    },
    // 存在夏令时的UTC
    handleGetDSTUTCObj(valueLabel) {
      let realUTCTime = moment
        .tz(valueLabel, null, this.timeZone)
        .utc()
        .clone()
        .add(1, 'hour');

      let tmpFormat = moment
        .tz(realUTCTime, null, this.timeZone)
        .format(this.$attrs.format);

      return {
        realUTCTime,
        tmpFormat,
      };
    },

    _getUTC(timeValue) {
      let timeLabel = this.getFormatLabel(timeValue);
      return moment.tz(timeLabel, null, this.timeZone).utc();
    },

    _showDSTLabel(show) {
      let stampSuffix = show ? '[(DST)]' : '';
      this.curformat = `${this.$attrs.format} ${stampSuffix}`;
    },

    isDSTFun() {
      let timeLabel = this.getFormatLabel();
      console.log('formLabel', timeLabel);
      return moment.tz(timeLabel, null, this.timeZone).isDST();
    },

    getFormatLabel(timeParam) {
      let valueParam = timeParam || this.curValue;
      let tmpFormat = this.$attrs.valueFormat || this.curValueformat;
      if (typeof valueParam === 'number' && !isNaN(valueParam)) {
        // 判断长度 毫秒是13位 秒是 10位
        const timestampStr = valueParam.toString();
        if (timestampStr.length === 10) {
          valueParam = valueParam * 1000;
        }
        return moment(valueParam).format(tmpFormat);
      } else {
        return moment(valueParam).format(tmpFormat);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.time-wrapper {
  :deep(.after-wrapper) {
    font-size: 12px;
  }
}
</style>
